/**     
* @Title: MyAccessDecisionManager.java   
* @Package me.security.example.security   
* @Description: TODO   
* @author xaoyaoyao
* @date 2017年8月23日 下午4:42:42
*/
package me.security.example.security;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

/**
 * @ClassName: MyAccessDecisionManager
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2017年8月23日 下午4:42:42
 * 
 */
@Service
public class MyAccessDecisionManager implements AccessDecisionManager {

	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException {
		HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
		String url, method;
		if ("anonymousUser".equals(authentication.getPrincipal()) || matchers("/images/**", request)
				|| matchers("/js/**", request) || matchers("/css/**", request) || matchers("/fonts/**", request)
				|| matchers("/", request) || matchers("/index.html", request) || matchers("/favicon.ico", request)
				|| matchers("/login", request)) {
			return;
		} else {
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (ga instanceof MyGrantedAuthority) {
					MyGrantedAuthority urlGrantedAuthority = (MyGrantedAuthority) ga;
					url = urlGrantedAuthority.getPermissionUrl();
					method = urlGrantedAuthority.getMethod();
					if (matchers(url, request)) {
						if (method.equals(request.getMethod()) || "ALL".equals(method)) {
							return;
						}
					}
				}
			}
		}
		throw new AccessDeniedException("Access Denied");
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	private boolean matchers(String url, HttpServletRequest request) {
		AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
		if (matcher.matches(request)) {
			return true;
		}
		return false;
	}
}